package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.DTO.property.PropertyCarGetOneDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyCarGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyCarSaveDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyCarUpdateDTO;
import com.itlong.cloud.POJO.PO.PropertyCarManagePO;
import com.itlong.cloud.POJO.VO.property.PropertyCarGetOneVO;
import com.itlong.cloud.POJO.VO.property.PropertyCarGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.property.dao.IPropertyCarDao;
import com.itlong.cloud.property.dao.IPropertyParkingDao;
import com.itlong.cloud.property.service.IPropertyCarService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      物业管理-车辆管理服务层接口实现类
 * </desc>
 *
 * @createDate 2018/08/17
 */
@Service
public class PropertyCarServiceImpl implements IPropertyCarService {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyCarServiceImpl.class);

    @Autowired
    private IPropertyCarDao iPropertyCarDao;

    @Autowired
    private IPropertyParkingDao iPropertyParkingDao;

    private static ExecutorService importAddressFixedThreadPool = Executors.newFixedThreadPool(12); //导入车辆的线程池

    /**
     * <desc>
     *      获取单个车辆信息
     * </desc>
     *
     * @param propertyCarGetOneDTO 获取单个车辆信息查询参数DTO
     * @return 单个车辆信息
     * @author wangzhi
     * @createDate 2018/08/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyCarGetOneVO getOneCar(PropertyCarGetOneDTO propertyCarGetOneDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyCarGetOneDTO);
        PropertyCarGetOneVO propertyCarGetOneVO = iPropertyCarDao.getOneBasicCar(params);
        if (propertyCarGetOneVO != null && StringUtils.isNotBlank(propertyCarGetOneVO.getParkingId())) {
            List<String> parkingIds = StringHandlerUtil.splitStringList(propertyCarGetOneVO.getParkingId());
            String parkingNum = iPropertyParkingDao.getParkingNumByIds(parkingIds);
            propertyCarGetOneVO.setParkingNum(parkingNum);
        }
        return propertyCarGetOneVO;
    }

    /**
     * <desc>
     *      分页获取车辆信息
     * </desc>
     *
     * @param propertyCarGetPageDTO 查询参数
     * @return 分页结果
     * @author wangzhi
     * @createDate 2018/08/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyCarGetPageVO> getCarsByPage(PropertyCarGetPageDTO propertyCarGetPageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyCarGetPageDTO);

        // 带车位号模糊查询，因数据库中数据结构的问题，分开特殊处理
        if (StringUtils.isNotBlank(propertyCarGetPageDTO.getParkingNum())) {
            Page<PropertyCarGetPageVO> page = new Page<>();
            page.getPage().setPageSize(propertyCarGetPageDTO.getPageSize());
            page.getPage().setCurrentPage(propertyCarGetPageDTO.getCurrentPage());
            List<PropertyCarGetPageVO> propertyCarGetPageVOS = iPropertyCarDao.getAllCars(params);
            List<PropertyCarGetPageVO> propertyCarGetPageVOList = new ArrayList<>();
            List<PropertyCarGetPageVO> propertyCarGetPageVOReturn = new ArrayList<>();
            for (PropertyCarGetPageVO propertyCarGetPageVO : propertyCarGetPageVOS){
                if (StringUtils.isBlank(propertyCarGetPageVO.getParkingNum()) && StringUtils.isNotBlank(propertyCarGetPageVO.getParkingId())) {
                    String parkingNum = iPropertyParkingDao.getParkingNumByIds(StringHandlerUtil.splitStringList(propertyCarGetPageVO.getParkingId()));
                    propertyCarGetPageVO.setParkingNum(parkingNum);
                }
                // 过滤车位号
                if (StringUtils.isNotBlank(propertyCarGetPageVO.getParkingNum()) && propertyCarGetPageVO.getParkingNum().contains(propertyCarGetPageDTO.getParkingNum())) {
                    propertyCarGetPageVOList.add(propertyCarGetPageVO);
                }
            }
            // 进行分页操作
            for (int index = page.getPage().getStartSlip(); index < page.getPage().getStartSlip() + page.getPage().getPageSize(); index++) {
                if (propertyCarGetPageVOList.size() > index) {
                    propertyCarGetPageVOReturn.add(propertyCarGetPageVOList.get(index));
                } else {
                    break;
                }
            }
            page.setRows(propertyCarGetPageVOReturn,propertyCarGetPageVOList.size());
            return page;
        }

        Page<PropertyCarGetPageVO> page = new Page<>();
        page.getPage().setPageSize(propertyCarGetPageDTO.getPageSize());
        page.getPage().setCurrentPage(propertyCarGetPageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<PropertyCarGetPageVO> propertyCarGetPageVOS = iPropertyCarDao.getCarsByPage(params);
        for (PropertyCarGetPageVO propertyCarGetPageVO : propertyCarGetPageVOS){
            if (StringUtils.isBlank(propertyCarGetPageVO.getParkingNum()) && StringUtils.isNotBlank(propertyCarGetPageVO.getParkingId())) {
                String parkingNum = iPropertyParkingDao.getParkingNumByIds(StringHandlerUtil.splitStringList(propertyCarGetPageVO.getParkingId()));
                propertyCarGetPageVO.setParkingNum(parkingNum);
            }
        }
        page.setRows(propertyCarGetPageVOS,iPropertyCarDao.getCarsRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      添加车辆信息
     * </desc>
     *
     * @param propertyCarSaveDTO 添加参数
     * @return 受影响的行数
     * @author wangzhi
     * @createDate 2018/08/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveCar(PropertyCarSaveDTO propertyCarSaveDTO) throws Exception {
        Date nowTime = new Date();
        PropertyCarManagePO propertyCarManagePO = new PropertyCarManagePO();
        BeanUtils.copyProperties(propertyCarSaveDTO,propertyCarManagePO);
        propertyCarManagePO.setCarId(LogicIdUtil.bussinessId());
        propertyCarManagePO.setStatus(DataStatusEnum.NORMAL.getType());
        propertyCarManagePO.setCreateTime(nowTime);
        propertyCarManagePO.setUpdateTime(nowTime);
        return iPropertyCarDao.saveCar(SqlUtil.durableData(propertyCarManagePO,PlatformConstants.TABLE_SAVE));
    }

    /**
     * <desc>
     *      删除车辆，含批量删除
     * </desc>
     *
     * @param carIds 车辆id，多个用英文","相连
     * @return 受影响的行数
     * @author wangzhi
     * @createDate 2018/08/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deleteCars(String carIds) throws Exception {
        List<String> carIdList = StringHandlerUtil.splitStringList(carIds);
        return iPropertyCarDao.deleteCars(carIdList);
    }

    /**
     * <desc>
     *      修改车辆
     * </desc>
     *
     * @param propertyCarUpdateDTO 修改参数DTO
     * @return 受影响的行数
     * @author wangzhi
     * @createDate 2018/08/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateCar(PropertyCarUpdateDTO propertyCarUpdateDTO) throws Exception {
        Date nowTime = new Date();
        PropertyCarManagePO propertyCarManagePO = new PropertyCarManagePO();
        BeanUtils.copyProperties(propertyCarUpdateDTO,propertyCarManagePO);
        propertyCarManagePO.setProjectId(null);
        propertyCarManagePO.setPlateNumber(null);
        propertyCarManagePO.setUpdateTime(nowTime);
        Map<String,Object> map = SqlUtil.durableData(propertyCarManagePO,PlatformConstants.TABLE_UPDATE);
        return iPropertyCarDao.updateCar(map);
    }

    /**
     * <desc>
     *      查询所有车辆
     * </desc>
     *
     * @param propertyCarGetPageDTO 查询参数
     * @return 车辆集合
     * @author wangzhi
     * @createDate 2018/08/23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<PropertyCarGetPageVO> getAllCars(PropertyCarGetPageDTO propertyCarGetPageDTO) throws Exception {
        if (StringUtils.isBlank(propertyCarGetPageDTO.getCarIds())) {
            Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyCarGetPageDTO);

            // 带车位号模糊查询，因数据库中数据结构的问题，分开特殊处理
            if (StringUtils.isNotBlank(propertyCarGetPageDTO.getParkingNum())) {
                List<PropertyCarGetPageVO> propertyCarGetPageVOS = iPropertyCarDao.getAllCars(params);
                List<PropertyCarGetPageVO> propertyCarGetPageVOList = new ArrayList<>();
                for (PropertyCarGetPageVO propertyCarGetPageVO : propertyCarGetPageVOS){
                    if (StringUtils.isBlank(propertyCarGetPageVO.getParkingNum()) && StringUtils.isNotBlank(propertyCarGetPageVO.getParkingId())) {
                        String parkingNum = iPropertyParkingDao.getParkingNumByIds(StringHandlerUtil.splitStringList(propertyCarGetPageVO.getParkingId()));
                        propertyCarGetPageVO.setParkingNum(parkingNum);
                    }
                    // 过滤车位号
                    if (StringUtils.isNotBlank(propertyCarGetPageVO.getParkingNum()) && propertyCarGetPageVO.getParkingNum().contains(propertyCarGetPageDTO.getParkingNum())) {
                        propertyCarGetPageVOList.add(propertyCarGetPageVO);
                    }
                }
                return propertyCarGetPageVOList;
            }

            List<PropertyCarGetPageVO> propertyCarGetPageVOS = iPropertyCarDao.getAllCars(params);
            for (PropertyCarGetPageVO propertyCarGetPageVO : propertyCarGetPageVOS){
                if (StringUtils.isBlank(propertyCarGetPageVO.getParkingNum()) && StringUtils.isNotBlank(propertyCarGetPageVO.getParkingId())) {
                    String parkingNum = iPropertyParkingDao.getParkingNumByIds(StringHandlerUtil.splitStringList(propertyCarGetPageVO.getParkingId()));
                    propertyCarGetPageVO.setParkingNum(parkingNum);
                }
            }
            return propertyCarGetPageVOS;
        }
        List<String> carIds = StringHandlerUtil.splitStringList(propertyCarGetPageDTO.getCarIds());
        List<PropertyCarGetPageVO> propertyCarGetPageVOS = iPropertyCarDao.getCarsByIds(carIds);
        for (PropertyCarGetPageVO propertyCarGetPageVO : propertyCarGetPageVOS){
            if (StringUtils.isBlank(propertyCarGetPageVO.getParkingNum()) && StringUtils.isNotBlank(propertyCarGetPageVO.getParkingId())) {
                String parkingNum = iPropertyParkingDao.getParkingNumByIds(StringHandlerUtil.splitStringList(propertyCarGetPageVO.getParkingId()));
                propertyCarGetPageVO.setParkingNum(parkingNum);
            }
        }
        return propertyCarGetPageVOS;
    }

    /**
     * <desc>
     *      批量保存车辆信息
     * </desc>
     *
     * @param propertyCarSaveDTOList 车辆信息集合
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2018/08/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer batchSaveCars(List<PropertyCarSaveDTO> propertyCarSaveDTOList) throws Exception {
        List<PropertyCarManagePO> propertyCarManagePOS = new ArrayList<>();
        importAddressFixedThreadPool.execute(()-> {
            try {
                Date nowTime = new Date();
                for (PropertyCarSaveDTO propertyCarSaveDTO : propertyCarSaveDTOList){
                    PropertyCarManagePO propertyCarManagePO = new PropertyCarManagePO();
                    BeanUtils.copyProperties(propertyCarSaveDTO,propertyCarManagePO);
                    propertyCarManagePO.setCarId(LogicIdUtil.bussinessId());
                    propertyCarManagePO.setStatus(DataStatusEnum.NORMAL.getType());
                    propertyCarManagePO.setCreateTime(nowTime);
                    propertyCarManagePO.setUpdateTime(nowTime);
                    propertyCarManagePOS.add(propertyCarManagePO);
                }
                iPropertyCarDao.batchSaveCars(propertyCarManagePOS);
            } catch (Exception e) {
                LOG.error("导入车辆信息失败", e);
            }
        });
        return propertyCarSaveDTOList.size();
    }

    /**
     * <desc>
     *      查询所有车牌号
     * </desc>
     *
     * @param projectId 项目编号
     * @return 项目下所有车牌号
     * @author wangzhi
     * @createDate 2019/01/07
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getAllPlateNumberByProjectId(String projectId) throws Exception {
        return iPropertyCarDao.getAllPlateNumberByProjectId(projectId);
    }
}
